package br.com.fiap.dao.impl;

import java.util.List;

import javax.inject.Inject;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import br.com.fiap.beans.filtro.FiltroTrecho;
import br.com.fiap.dao.TrechoDAO;
import br.com.fiap.dao.VooDAO;
import br.com.fiap.entity.Trecho;
import br.com.fiap.entity.Voo;

public class TrechoDAOImpl extends AbstractDAOImpl<Trecho> implements TrechoDAO {

	private static final long serialVersionUID = -1111279587510577007L;
	
	@Inject
	private VooDAO vooDAO;
	
//	@Override
//	public final void saveOrUpdate(Trecho trecho) {
//		
//		Session session = this.getHibernateSession();
//		
//		session.getTransaction().begin();
//		
//		Voo persistedVoo = vooDAO.findById(trecho.getVoo().getNumero());
//		Trecho persistedTrecho = this.findById(trecho.getId());
//		
//		BeanUtils.copyProperties(trecho, persistedTrecho);
//		
//	}
	
	public List<Trecho> findByFilter(final FiltroTrecho filtro) {
		
		Session session = this.getHibernateSession();
		
		StringBuilder sql = new StringBuilder();
		
		sql.append(" select t from " + Trecho.class.getCanonicalName() + " t ");
		
		boolean putWhereCaluse = true;
		
		if (filtro.getVoo() != null && filtro.getVoo().getNumero() != null && filtro.getVoo().getNumero() != 0) {
			if (putWhereCaluse) {
				sql.append(" where voo = :voo ");
				putWhereCaluse = false;
			} else {
				sql.append(" and voo = :voo ");
			}
		}
		
		if (filtro.getDataFim() != null
				&& filtro.getDataInicio() != null) {
			if (putWhereCaluse) {
				sql.append(" where data between :dataInicio and :dataFim ");
				putWhereCaluse = false;
			} else {
				sql.append(" and data between :dataInicio and :dataFim ");
			} 
		}
		
		Query query = session.createQuery(sql.toString());
		
		if (filtro.getVoo() != null && filtro.getVoo().getNumero() != null && filtro.getVoo().getNumero() != 0) {
			query.setParameter("voo", filtro.getVoo());
		}
		
		if (filtro.getDataFim() != null
				&& filtro.getDataInicio() != null) {
			query.setParameter("dataInicio", filtro.getDataInicio());
			query.setParameter("dataFim", filtro.getDataFim());
		}
		
		List<Trecho> list = query.list();
		
		return list;
		
	}

	public List<Trecho> findByNumero(Integer numero) {
		
		Session session = this.getHibernateSession();
		
		StringBuilder sql = new StringBuilder();
		
		sql.append(" select v from " + Trecho.class.getCanonicalName() + " v ");
		
		if (numero != null) {
			sql.append(" where v.numero = :numero ");
		}
		
		Query query = session.createQuery(sql.toString());
		
		if (numero != null) {
			query.setParameter("numero", numero);
		}

		List<Trecho> trechos = (List<Trecho>) query.list();
		
		session.clear();
		session.close();
		
		return trechos;
		
	}

	@Override
	public Class<Trecho> getEntityClass() {
		return Trecho.class;
	}

}
